package com.wyix.aop;

import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Date;
import java.util.stream.Collectors;

/**
 * @author wangdx
 * @since 2025/8/6
 */
public class CglibProxyInterceptor implements MethodInterceptor {
    private final Object target;  // 被代理对象

    public CglibProxyInterceptor(Object target) {
        this.target = target;
    }

    @Override
    public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        // 前置通知：日志记录
        String methodName = method.getName();
        System.out.println("\n[CGLIB前置通知] 时间：" + new Date() + " 调用方法：" + methodName + " 参数：" + String.join(",", (String) args[0], String.valueOf(args[1])));

        System.out.println(Arrays.stream(args).map(String::valueOf).collect(Collectors.joining(",")));
        Object result;
        try {
            // 执行原始方法（通过methodProxy调用效率更高）
            result = methodProxy.invoke(target, args);

            // 后置通知：记录结果
            System.out.println("[CGLIB后置通知] 方法：" + methodName + " 执行结果：" + result);
        } catch (IllegalArgumentException e) {
            // 异常通知：捕获非法参数异常
            System.out.println("[CGLIB异常通知] 方法执行出错：" + e.getMessage());
            result = "错误：参数不合法（VIP等级1-5级）";
        }

        return result;
    }
}
